package lv.solcraft.replication.server.scheduler;

import lv.solcraft.replication.server.api.CleanExpiredOpers;
import lv.solcraft.replication.server.api.CleanFinishedOpers;
import lv.solcraft.replication.server.boot.ServerConfig;

import org.apache.log4j.Logger;

public class ScheduledOpersCleaner implements Scheduled {

    private static final Logger log = Logger.getLogger(ScheduledOpersCleaner.class);

    private ServerConfig serverConfig;

    private CleanExpiredOpers cleanExpiredOpers;

    private CleanFinishedOpers cleanFinishedOpers;

    public void setCleanExpiredOpers(CleanExpiredOpers cleanExpiredOpers) {
        this.cleanExpiredOpers = cleanExpiredOpers;
    }

    public void setCleanFinishedOpers(CleanFinishedOpers cleanFinishedOpers) {
        this.cleanFinishedOpers = cleanFinishedOpers;
    }

    public void setServerConfig(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }

    public void execute() throws Exception {
        try {
            cleanExpiredOpers.delete(serverConfig.calculateOpersExpireTime());
        } catch (Exception e) {
            log.error("Expired opers cleaner failed", e);
        }
        try {
            cleanFinishedOpers.delete(serverConfig.calculateFinishedOpersExpireTime());
        } catch (Exception e) {
            log.error("Finished opers cleaner failed", e);
        }
    }

    public String getCron() {
        return serverConfig.getOpersCleanerCron();
    }
}
